package com.cow.sram.module.archives;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cow.framework.core.exception.BusinessException;
import com.cow.framework.utils.encrypt.MD5Util;
import com.cow.framework.utils.json.FastJsonUtil;
import com.cow.framework.utils.math.MathUtil;
import com.cow.framework.utils.reflection.MapToBeanUtil;
import com.cow.framework.utils.web.IPUtil;
import com.cow.framework.utils.web.SessionUtil;
import com.cow.framework.core.base.BaseComponent;
import com.cow.sram.comm.config.constant.MessageConstants;
import com.cow.sram.comm.utils.SmsUtil;
import com.cow.sram.data.dao.OperatelogDAO;
import com.cow.sram.data.entity.Operatelog;
import com.cow.sram.data.entity.Userinfo;
import com.cow.sram.module.distribution.UserroleService;
import com.github.pagehelper.PageInfo;;
/**
 * 用户控制类
 * @author Administrator
 *
 */
@RestController
@EnableAutoConfiguration
@Transactional
@RequestMapping(value="/archives")
public class UserInfoController  extends BaseComponent{

	@Autowired
	UserInfoService userInfoService;
	@Autowired
	UserroleService userroleService;
	@Autowired
	SmsUtil smsUtil;
	@Autowired
	OperatelogDAO operatelogDAO;
	
	/**列表显示*/
	@RequestMapping(value="/queryUserInfoAll")
	public Object queryUserInfoAll(@RequestBody Map parmMap){
		List<Map> list = userInfoService.queryAlluserInfo(parmMap);
		return new PageInfo<Map>(list);
	}
	
	
	/**根据ID查看用户*/
	@RequestMapping(value="/getUserInfoById")
	public Object getUserInfoById(@RequestParam Integer id){
		return userInfoService.getUserMapByID(id);
	}
		
	/**新增用户*/
	@RequestMapping(value="/saveUserInfo")
	public Object saveUserInfo(@RequestBody Userinfo us){
		   Map parm=new HashMap();
			String pass=MathUtil.getRandStr(8);
			us.setPassword(MD5Util.crypt(pass));
			us.setLockflag("0");
			us.setRegisttime(new Date());
			us.setCreator(super.getCurUserId());
	     	userInfoService.saveUserInfo(us);
	     	//短信通知
			if(active.equals("prod")||active.equals("test")){//生产环境才发短信
				Map params = new HashMap<String,String>();
		    	params.put("account", us.getAccountname());
		    	params.put("password", pass);
				try {
					smsUtil.sendSms(us.getAccountname(), "SMS_85270013", FastJsonUtil.collectToString(params));
				} catch (Exception e) {
					e.printStackTrace();
				}														
			}	
			parm.put("userid", us.getUserid());
			parm.put("pass", pass);
			 // 接收到请求，记录请求内容
	        HttpServletRequest request = SessionUtil.getRequest();        
	        String ip = IPUtil.getIpAddress(request);
	        String uri = request.getRequestURI();
			//记录访问日志
        	Operatelog log = new Operatelog();
        	log.setAccountname(us.getAccountname());
        	log.setResourcepath(uri + "******userid:"+us.getUserid() +" 账户:"+us.getAccountname());
        	log.setOpername("新增用户");
        	log.setOperip(ip);
        	log.setOpertime(new Date());
        	operatelogDAO.save(log); 
        	
	     	return parm;
	}
	

	
	/**重置密码*/
	@RequestMapping(value="/resetPass")	
	public Object resetPass(@RequestParam String checkCode,String phone,String pass){	
		if(checkCode == null || super.getCache("checkCode", checkCode)==null){//验证码无效或已过期
			throw new BusinessException("B1002",MessageConstants.B1002);
		}
		Userinfo us = userInfoService.getUserInfoByAccountname(phone);
		us.setPassword(pass);
		userInfoService.editUserInfo(us);
		return "success";
	
	}
	
	/**密码修改*/
	@RequestMapping(value="/modifyPassword")	
	public Object modifyPassword(@RequestParam String oldPassword,@RequestParam String newPassword) throws Exception{
		String result = super.getAuthClient().modifyPassword(super.getCurUserId(), oldPassword, newPassword);
		if(result.equals("1")){
			result = "success";			
		}else if(result.equals("02")){
			throw new BusinessException("B1013",MessageConstants.B1013);
		}
		return result;
	}
	
	/**获取验证码*/
	@RequestMapping(value="/getCheckCode")	
	public Object getCheckCode(@RequestParam String phone) throws Exception{	
		Userinfo us = userInfoService.getUserInfoByAccountname(phone);
		if(us==null){
			throw new BusinessException("B1020",MessageConstants.B1020);
		}
		//生成邀请码
		Integer code = MathUtil.randomInt(100000, 999999);		
		//写缓存
		super.setCache("checkCode", code.toString(), code.toString());
		//短信通知
		if(active.equals("prod")||active.equals("test")){//生产环境才发短信
			Map params = new HashMap<String,String>();
	    	params.put("validcode", code);
			try {
				smsUtil.sendSms(phone, "SMS_85320016", FastJsonUtil.collectToString(params));
			} catch (Exception e) {
				e.printStackTrace();
			}														
		}	
		return "success";
	}
	
	/**修改用户*/
	@RequestMapping(value="/editUserInfo")
	public Object editUserInfo(@RequestBody Map parmMap){
		Userinfo us = userInfoService.getUserInfoByID(Integer.valueOf(parmMap.get("userid").toString()));
		MapToBeanUtil.copyMapToBean(parmMap, us);
		userInfoService.editUserInfo(us);
		return "success";
	}
	
	/**删除用户*/
	@RequestMapping(value="/delUserInfo")
	public Object delUserInfo(@RequestParam Integer id){
		userroleService.delUserId(id);
		userInfoService.delUserInfo(id);
		 // 接收到请求，记录请求内容
        HttpServletRequest request = SessionUtil.getRequest();        
        String ip = IPUtil.getIpAddress(request);
        String uri = request.getRequestURI();
		//记录访问日志
    	Operatelog log = new Operatelog();
    	log.setAccountname(super.getCurUser().getAccountname());
    	log.setResourcepath(uri + "******userid:"+id);
    	log.setOpername("删除用户");
    	log.setOperip(ip);
    	log.setOpertime(new Date());
    	operatelogDAO.save(log); 
		return "success";
	}
	 
}
